package com.zipsted.proto;

import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.World;

import javax.media.opengl.*;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.glu.GLU;

/**
 * Created by zipSTED LLC.
 * User: edgar
 * Date: 13.10.11
 * Time: 16:43
 */
public abstract class Renderer extends GLCanvas implements GLEventListener {
  public final World WORLD = new World(
      new Vec2(0.0f, -10.0f),   // gravity vector
      true                      // enable sleep mode
  );

  public static final int RENDER_WIDTH = 480;
  public static final int RENDER_HEIGHT = 320;

  private static final GLCapabilities capabilities = new GLCapabilities(GLProfile.get(GLProfile.GL2));
  private static final GLU GLU_CLIENT = new GLU();

  public Renderer() {
    this(capabilities);
  }

  public Renderer(GLCapabilities capabilities) {
    super(capabilities);
    this.addGLEventListener(this);
    this.setSize(RENDER_WIDTH, RENDER_HEIGHT);
  }

  public void display(GLAutoDrawable drawable) {
    final GL2 gl = drawable.getGL().getGL2();
    gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
    gl.glLoadIdentity();
    gl.glTranslatef(0.0f, 4.0f, 0.0f);
//    WORLD.drawDebugData();
    gl.glFlush();
  }

  @Deprecated
  public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
    System.out.println("displayChanged called");
  }

  @Override
  public void init(GLAutoDrawable drawable) {
    System.out.println("init() called");
    GL2 gl = drawable.getGL().getGL2();
    gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    gl.glShadeModel(GL2.GL_FLAT);
  }

  @Override
  public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
    System.out.println("reshape() called: x = " + x + ", y = " + y + ", width = " + width + ", height = " + height);
    final GL2 gl = drawable.getGL().getGL2();

    if (height <= 0) {
      height = 1;
    }

    final float h = (float) width / (float) height;

    gl.glViewport(0, 0, width, height);
    gl.glMatrixMode(GL2.GL_PROJECTION);
    gl.glLoadIdentity();
    GLU_CLIENT.gluPerspective(45.0f, h, 1.0, 20.0);
    gl.glMatrixMode(GL2.GL_MODELVIEW);
    gl.glLoadIdentity();
  }

  @Override
  public void dispose(GLAutoDrawable arg0) {
    System.out.println("dispose() called");
  }
}
